package cn.stylefeng.guns.sys.modular.dataClean.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.modular.cleanRule.model.params.CleanRuleParam;
import cn.stylefeng.guns.sys.modular.cleanRule.model.result.CleanRuleResult;
import cn.stylefeng.guns.sys.modular.cleanRule.service.CleanRuleService;
import cn.stylefeng.guns.sys.modular.dataClean.entity.DataClean;
import cn.stylefeng.guns.sys.modular.dataClean.mapper.DataCleanMapper;
import cn.stylefeng.guns.sys.modular.dataClean.model.params.DataCleanParam;
import cn.stylefeng.guns.sys.modular.dataClean.model.result.DataCleanResult;
import cn.stylefeng.guns.sys.modular.dataClean.service.DataCleanService;
import cn.stylefeng.guns.sys.modular.dataManagement.model.params.StandardManagementParam;
import cn.stylefeng.guns.sys.modular.dataManagement.model.result.StandardManagementResult;
import cn.stylefeng.guns.sys.modular.dataManagement.service.StandardManagementService;
import cn.stylefeng.guns.sys.modular.dataQualityCheck.entity.EtlJob;
import cn.stylefeng.guns.sys.modular.dataQualityCheck.model.params.QualityCheckParam;
import cn.stylefeng.guns.sys.modular.dbServicelist.model.params.DbServicelistParam;
import cn.stylefeng.guns.sys.modular.dbServicelist.model.result.DbServicelistResult;
import cn.stylefeng.guns.sys.modular.dbServicelist.service.DbServicelistService;
import cn.stylefeng.guns.sys.modular.dbservicedetails.model.params.DbServicedetailsParam;
import cn.stylefeng.guns.sys.modular.dbservicedetails.model.result.DbServicedetailsResult;
import cn.stylefeng.guns.sys.modular.dbservicedetails.service.DbServicedetailsService;
import cn.stylefeng.guns.sys.modular.metadata.model.params.MetadataParam;
import cn.stylefeng.guns.sys.modular.metadata.model.result.MetadataResult;
import cn.stylefeng.guns.sys.modular.metadata.service.MetadataService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * <p>
 * 数据清洗表 服务实现类
 * </p>
 *
 * @author author
 * @since 2020-11-19
 */
@Service
public class DataCleanServiceImpl extends ServiceImpl<DataCleanMapper, DataClean> implements DataCleanService {

    @Autowired
    private MetadataService metadataService;

    @Autowired
    private DbServicelistService dbServicelistService;

    @Autowired
    private DbServicedetailsService dbServicedetailsService;

    @Autowired
    private CleanRuleService cleanRuleService;

    @Override
    public void add(DataCleanParam param) {
        DataClean entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(DataCleanParam param) {
        this.removeById(getKey(param));
    }

    @Override
    public void update(DataCleanParam param) {
        DataClean oldEntity = getOldEntity(param);
        DataClean newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public DataCleanResult findBySpec(DataCleanParam param) {
        return null;
    }

    @Override
    public List<DataCleanResult> findListBySpec(DataCleanParam param) {
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(DataCleanParam param) {
        param.setIsDelete(1);
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public int cleanMetadata(MetadataParam param) {
        //判断是否成功清洗标识
        int isSuccess = 0;
        //先通过元数据名id查询到数据库详细信息
        List<MetadataResult> list = metadataService.findListBySpec(param);
        //通过表名获取到数据库id
        DbServicedetailsParam dbServicedetailsParam = new DbServicedetailsParam();
        dbServicedetailsParam.setTableName(list.get(0).getTableName());
        List<DbServicedetailsResult> list1 = dbServicedetailsService.findListBySpec(dbServicedetailsParam);
        //通过数据库id查询数据库中的jdbc_url
        DbServicelistParam dbServicelistParam = new DbServicelistParam();
        dbServicelistParam.setId(list1.get(0).getServiceId());
        List<DbServicelistResult> list2 = dbServicelistService.findListBySpec(dbServicelistParam);

        //注册申请的时候需要抓取数据
        //将申请的数据放到etl_job表中
        EtlJob etlJob = new EtlJob();
        Random random = new Random();
        int y = 0;
        String x = "";
        do {
            y = random.nextInt(1000000000);
            x = "j" + String.valueOf(y);
            etlJob.setJobId(x);
        }
        while (this.baseMapper.searchEtlJob(etlJob).size() > 0);
        etlJob.setMetadataId(String.valueOf(param.getMetadataId()));
        etlJob.setToDsId("0");
        etlJob.setFromDsId(String.valueOf(list2.get(0).getId()));
        etlJob.setJobName(list.get(0).getMetadataName() + "的清洗检查");
        this.baseMapper.insertEtlJob(etlJob);

        //获取到刚添加到etl_job表中的id
        List<EtlJob> listEtlJob = this.baseMapper.searchEtlJob(etlJob);
        //获取数据
        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        //TODO 部署的时候这个地方要改成调用迁数据项目的地址
        HttpPost httppost = new HttpPost("http://172.16.0.157:9000/ETLEngine/api/job/startJOb");
        // 创建参数队列
        List<BasicNameValuePair> formParams = new ArrayList<BasicNameValuePair>();
        formParams.add(new BasicNameValuePair("jobid", listEtlJob.get(0).getJobId()));
        //runType为的时候是数据质量检查
        formParams.add(new BasicNameValuePair("runType", "2"));
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
            httppost.setEntity(uefEntity);
            System.out.println("executing request " + httppost.getURI());
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    System.out.println("--------------------------------------");
                    System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
                    System.out.println("--------------------------------------");
                }
            } finally {
                response.close();
            }
        } catch (ClientProtocolException e) {
            isSuccess = 1;
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            isSuccess = 1;
            e1.printStackTrace();
        } catch (IOException e) {
            isSuccess = 1;
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //如果清洗成功
        //发送检查请求后进行清洗表数据的添加
        if (isSuccess == 0) {
            DataCleanParam dataCleanParam = new DataCleanParam();
            dataCleanParam.setMetadataName(list.get(0).getMetadataName());
            List<DataCleanResult> list4 = this.baseMapper.customList(dataCleanParam);
            if (list4.size() != 0) {
                this.baseMapper.deleteById(list4.get(0).getDataDataCleanId());
                EtlJob etlJob1 = new EtlJob();
                etlJob1.setJobId(list4.get(0).getJobId());
                this.baseMapper.deleteEtlJob(etlJob1);
            }
            //获取到所有标准
            List<CleanRuleResult> list3 = cleanRuleService.findListBySpec(new CleanRuleParam());
            String standard = "";
            for (int i = 0; i < list3.size(); i++) {
                standard = standard + list3.get(i).getDataCleanRuleName() + ",";
                if (i == list3.size() - 1) {
                    standard = standard + list3.get(i).getDataCleanRuleName();
                }
            }
            dataCleanParam.setJobId(x);
            dataCleanParam.setCleanRuleName(standard);
            dataCleanParam.setProblemDataNumber(0);
            dataCleanParam.setIsDelete(1);
            add(dataCleanParam);
            isSuccess = 200;
        }
        if (isSuccess == 1) {
            this.baseMapper.deleteEtlJob(etlJob);
            isSuccess = 500;
        }
        return isSuccess;
    }


    private Serializable getKey(DataCleanParam param) {
        return param.getDataDataCleanId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private DataClean getOldEntity(DataCleanParam param) {
        return this.getById(getKey(param));
    }

    private DataClean getEntity(DataCleanParam param) {
        DataClean entity = new DataClean();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
